var fs = require('fs')

var dbPath = './bd.json'

/**
 * 查找全部学生
 */
exports.find = function (callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        callback(null, JSON.parse(data).students)
    })
}

/**
 * 通过id查找学生
 */
exports.findById = function (id, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data).students
        var student = students.find(function (item) {
            return item.id === id;
        })
        callback(null, student)
    })
}

/**
 * 添加
 */
exports.add = function (student, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data).students
        student.id = students[students.length - 1].id + 1
        student.sex = Number(student.sex)
        students.push(student)
        console.log(students);
        var fileData = JSON.stringify({ "students": students })
        fs.writeFile(dbPath, fileData, function (err, data) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })
}

/**
 * 修改
 */
exports.updataById = function (student, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        student.id = parseInt(student.id)
        var students = JSON.parse(data).students
        var stu = students.find(function (item) {
            return item.id === student.id
        })
        for (var key in stu) {
            stu[key] = student[key]
        }
        var fileData = JSON.stringify({ "students": students })
        fs.writeFile(dbPath, fileData, function (err, data) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })
}

/**
 * 删除
 */
exports.deleteById = function (id, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data).students
        var deleteId = students.findIndex(function (item) {
            return item.id === id
        })
        students.splice(deleteId, 1)
        var fileData = JSON.stringify({ "students": students })
        fs.writeFile(dbPath, fileData, function (err, data) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })
}
